import { Component, OnInit } from '@angular/core';
// 导入表单相关：表单验证、表单构建、表单组
import { FormGroup, FormBuilder, Validators } from '@angular/forms';
import { NzSelectModule } from 'ng-zorro-antd/select';
import { EmailService } from 'src/app/core/service/email.service';
import { NzMessageService } from 'ng-zorro-antd';
@Component({
  selector: 'app-email-send-tab',
  templateUrl: './email-send-tab.component.html',
  styleUrls: ['./email-send-tab.component.scss']
})
export class EmailSendTabComponent implements OnInit {
  emailSendForm: FormGroup;
  checked = true;
  selectedValue = null;
  // select-part
  listOfOption = [];
  listOfSelectedValue = [];

  constructor(fb: FormBuilder, private emaiService: EmailService, private message: NzMessageService) {
    this.emailSendForm = fb.group({
      receiver: ['', Validators.required],
      sender: ['', Validators.required],
      theme: ['', Validators.required],
      emailContent: ['', Validators.required],
    });
  }

  ngOnInit() {
    this.getReceiverList();
  }
  //  弹窗
  createMessage(type: string, content?: string): void {
    if (type === 'success') {
      this.message.create(type, `发送成功!`, { nzDuration: 5000 });
    } else if (type === 'error') {
      this.message.create(type, `表单校验失败!请检查后重新提交`, { nzDuration: 5000 });
    } else if (type === 'warning') {
      this.message.create(type, `接口异常${content}`, { nzDuration: 5000 });
    }
  }
  // 获取收件人列表
  getReceiverList() {
    this.emaiService.getReceiverList().subscribe(selectData => {
      if (selectData.status === 1) {
        // select-part
        const children = [];
        for (let i = 0; i < selectData.data.length; i++) {
          children.push({ name: selectData.data[i].orgName, id: selectData.data[i].orgUuid });
        }
        this.listOfOption = children;
      }
    });
  }
  // 发送邮件
  sendEmail() {
    // tslint:disable-next-line: forin
    for (const c in this.emailSendForm.controls) {
      this.emailSendForm.controls[c].markAsTouched();
    }

    if (this.emailSendForm.valid) {
      let postData = {
        receiver: this.emailSendForm.value.receiver,
        // sender: this.emailSendForm.value.sender,
        subject: this.emailSendForm.value.theme,
        template: this.emailSendForm.value.emailContent,
        type: 'org'
      };
      console.log('send', postData);
      this.emaiService.sendEmail(postData).subscribe(data => {
        if (data.status === 1) {
          this.createMessage('success')
        } else {
          this.createMessage('warning', data.msg);
        }
      });
    } else {
      this.createMessage('error');
    }
  }
}
